import React, { useState } from 'react';
import './AuthForm.css';
import { useNavigate } from 'react-router-dom';
//逻辑已经处理完毕
const AuthForm = () => {
  const navigate = useNavigate();
  const [isLogin, setIsLogin] = useState(true);
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    confirmPassword: ''
  });
  const [message, setMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  // 处理输入变化
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // 处理注册
  const handleRegister = async (e) => {
    e.preventDefault();
    if (formData.password !== formData.confirmPassword) {
      setMessage('两次密码输入不一致');
      return;
    }
    setIsLoading(true);
    setMessage('正在注册...');
    try {
      const response = await fetch('http://localhost:5000/api/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: formData.email, password: formData.password }),
      });
       const responseData = await response.json();
       console.log(responseData);
      if (responseData.code===200) {
        setMessage('注册成功！请登录');
        setTimeout(() => {
          setIsLogin(true);
          setFormData({ ...formData, password: '', confirmPassword: '' });
          setMessage('');
        }, 2000);
      } else {
        setMessage('注册失败，请重试');
      }
    } catch (error) {
      setMessage('网络错误，请稍后再试');
    } finally {
      setIsLoading(false);
    }
  };

  // 处理登录：使用navigete跳转至主页面
  const handleLogin = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    setMessage('正在登录...');
    try {
      const response = await fetch('http://localhost:5000/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: formData.email, password: formData.password }),
      });
      console.log(response);
      const responseData = await response.json();
      if (responseData.code ===200) {
        console.log(responseData.code);

        localStorage.setItem('token', responseData.token); // 保存登录状态（刷新页面不丢失）
        setMessage('登录成功！正在进入...');
        // 关键：延迟 1.5 秒后调用回调，通知父组件登录成功
        setTimeout(() => {
          navigate(`/HeroSection?email=${formData.email}`);
        }, 1500);
      } else {
        setMessage('邮箱或密码错误');
      }
    } catch (error) {
      setMessage('网络错误，请稍后再试');
    } finally {
      setIsLoading(false);
    }
  };
  // 切换登录/注册模式：不变
  const toggleAuthMode = () => {
    setIsLogin(!isLogin);
    setFormData({ email: '', password: '', confirmPassword: '' });
    setMessage('');
  };
  // 组件渲染：不变
  return (
    <div className="auth-container">
      <div className="auth-card">
        <div className="fitness-icon">
          <div className="dumbbell-icon"></div>
        </div>
        <div className="auth-header">
          <h2>{isLogin ? '登录Endurance账号' : '创建Endurance账号'}</h2>
          <p>
            {isLogin ? '还没有Endurance账号？' : '已有Endurance账号？'}
            <button 
              type="button" 
              className="toggle-link" 
              onClick={toggleAuthMode}
              disabled={isLoading}
            >
              {isLogin ? '立即注册' : '立即登录'}
            </button>
          </p>
          {message && (
            <p className={message.includes('成功') ? 'success-message' : 'error-message'}>
              {message}
            </p>
          )}
        </div>
        <form 
          className="auth-form"
          onSubmit={isLogin ? handleLogin : handleRegister}
        >
          <div className="form-group">
            <label htmlFor="email">邮箱</label>
            <input
              type="email"
              id="email"
              name="email"
              value={formData.email}
              onChange={handleChange}
              disabled={isLoading}
              placeholder="请输入邮箱"
              required
            />
          </div>
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              name="password"
              value={formData.password}
              onChange={handleChange}
              disabled={isLoading}
              placeholder="请输入密码"
              required
            />
          </div>
          {!isLogin && (
            <div className="form-group">
              <label htmlFor="confirmPassword">确认密码</label>
              <input
                type="password"
                id="confirmPassword"
                name="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleChange}
                disabled={isLoading}
                placeholder="请再次输入密码"
                required
              />
            </div>
          )}
          <button 
            type="submit" 
            className="auth-button"
            disabled={isLoading}
          >
            {isLoading ? '处理中...' : isLogin ? '登录' : '注册'}
          </button>
        </form>
        <div className="fitness-motto">
          坚持锻炼，成就更好的自己！
        </div>
      </div>
    </div>
  );
};

export default AuthForm;